import csv
import random

# 加载CSV文件的数据
def load_words_from_csv(file_path):
    words = {}
    with open(file_path, 'r', encoding='utf-8') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            words[row['word']] = row['meaning']
    return words

# 随机选择三个词语
def get_random_words(word_dict, num=3):
    return random.sample(list(word_dict.keys()), num)

# 查看示意
def show_meaning(word, word_dict):
    return word_dict.get(word, "该词语不存在。")

# 主程序
def main():
    # 加载词典
    file_path = 'XDHYCD7th.csv'  # 替换为你的CSV文件的路径
    word_dict = load_words_from_csv(file_path)

    while True:
        print("请选择功能:")
        print("1. 随机造句")
        print("2. 词语示意")
        print("3. 退出")
        choice = input("请输入你的选择: ")

        if choice == '1':
            random_words = get_random_words(word_dict)
            print("随机生成的词语:", random_words)
            user_sentence = input("请根据这些词语造句，或输入‘sy’查看其中一个词的含义，或输入3退出: ")

            if user_sentence =='3':
                break
            # 如果用户输入的是“示意”，则查看示意
            while user_sentence == 'sy':
                word_to_show = input("请输入你想查看示意的词语: ")
                meaning = show_meaning(word_to_show, word_dict)
                user_sentence=input(f"{word_to_show} 的含义是: {meaning},请继续造句或输入‘sy’查看其中一个词的含义，或输入3退出: ")
                if user_sentence == '3':
                    exit()
            if user_sentence =='3':
                break
            # 在这里可以添加对句子的验证逻辑
            all_words_present = all(word in user_sentence for word in random_words)
            if all_words_present:
                print("造句成功！")
                continue_response = input("要继续造句吗？(y/n): ")
                if continue_response.lower() != 'y':
                    print("谢谢使用，再见！")
                    break
            else:
                print("错误，请再试一次。")

        elif choice == '2':
            word_to_show = input("请输入你想查看示意的词语: ")
            meaning = show_meaning(word_to_show, word_dict)
            print(f"{word_to_show} 的含义是: {meaning}")
        
        elif choice == '3':
            print("谢谢使用，再见！")
            break
        else:
            print("无效的选择，请重试。")

if __name__ == "__main__":
    main()